package com.yangye.cloud.demo.pay.scheduler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yangye.cloud.demo.pay.domain.Event;
import com.yangye.cloud.demo.pay.enums.EventTypeEnum;
import com.yangye.cloud.demo.pay.mapper.EventMapper;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author yangye
 * @date 2020/10/30
 */
@Component
public class PayScheduler {

	@Autowired
	private EventMapper eventMapper;
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@SneakyThrows
	@Scheduled(cron = "*/5 * * * * ?")
	@Transactional
	public void scheduledTask() {
		// 查询出所有状态为新建状态的事件
		Event query = new Event();
		query.setEventType(EventTypeEnum.NEW.getCode());

		List<Event> list = eventMapper.select(query);
		for (Event event : list) {
			// 更新事件表状态为已发送
			event.setEventType(EventTypeEnum.SENT.getCode());
			eventMapper.updateByPrimaryKey(event);

			// 发送消息到消息队列
			rabbitTemplate.convertAndSend("yangye-direct-exchange", "yangye-direct-routing-key", JSON.toJSONString(event));
		}
	}
}
